﻿/* Copyright 2007-2008 dnAnalytics Project.
 *
 * Contributors to this file:
 * Jurgen Van Gael
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 * 
 * * Redistributions of source code must retain the above copyright notice, this 
 *   list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above copyright notice, 
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 * * Neither the name of the dnAnalytics Project nor the names of its contributors
 *   may be used to endorse or promote products derived from this software without
 *   specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

using System;
using dnAnalytics.Math;
using dnAnalytics.Properties;

namespace dnAnalytics.Statistics.Distributions
{
    /// <summary>
    /// The Cauchy distribution is a symmetric continuous probability distribution.
    /// </summary>
    /// <remarks>The distribution will use the <see cref="System.Random"/> by default. 
    /// Users can set the random number generator by using the <see cref="RandomNumberGenerator"/> property.
    /// 
    /// The statistics classes will check all the incoming parameters whether they are in the allowed
    /// range. This might involve heavy computation. Optionally, by setting Control.CheckDistributionParameters
    /// to false, all parameter checks can be turned off.</remarks>
    public class Cauchy : IContinuousDistribution
    {
        // The location of the Cauchy distribution.
        private readonly double mLocation;

        // The scale of the Cauchy distribution.
        private readonly double mScale;

        /// <summary>
        /// Constructs a Cauchy distribution.
        /// </summary>
        /// <param name="location">The location parameter for the distribution.</param>
        /// <param name="scale">The scale parameter for the distribution.</param>
        /// <exception cref="ArgumentException">If <paramref name="stddev"/> is negative.</exception>
        public Cauchy(double location, double scale)
        {
            if (Control.CheckDistributionParameters)
            {
                CheckParameters(scale);
            }

            mLocation = location;
            mScale = scale;
            RandomNumberGenerator = new System.Random();
        }

        /// <summary>
        /// Gets the scale of the distribution.
        /// </summary>
        /// <value>The scale of the distribution.</value>
        public double Scale
        {
            get { return mScale; }
        }

        /// <summary>
        /// A string representation of the distribution.
        /// </summary>
        public override string ToString()
        {
            return "Cauchy(Location = " + mLocation + ", Scale = " + mScale + ")";
        }

        #region IDistribution Members

        /// <summary>
        /// Gets the mean of the distribution.
        /// </summary>
        /// <value>The mean of the distribution.</value>
        public double Mean
        {
            get { throw new NotSupportedException(); }
        }

        /// <summary>
        /// Gets the standard deviation of the distribution.
        /// </summary>
        /// <value>The standard deviation of the distribution.</value>
        public double StdDev
        {
            get { throw new NotSupportedException(); }
        }

        /// <summary>
        /// Gets the variance of the distribution.
        /// </summary>
        /// <value>The variance of the distribution.</value>
        public double Variance
        {
            get { throw new NotSupportedException(); }
        }

        /// <summary>
        /// The entropy of the distribution.
        /// </summary>
        /// <value></value>
        public double Entropy
        {
            get { return System.Math.Log(4.0 * Math.Constants.Pi * mScale); }
        }

        /// <summary>
        /// Gets or sets the random number generator.
        /// </summary>
        /// <value>The random number generator used to generate a random sample.</value>
        public System.Random RandomNumberGenerator { get; set; }

        #endregion

        #region IContinuousDistribution Members

        /// <summary>
        /// The mode of the distribution.
        /// </summary>
        /// <value></value>
        public double Mode
        {
            get { return mLocation; }
        }

        /// <summary>
        /// The median of the distribution.
        /// </summary>
        /// <value></value>
        public double Median
        {
            get { return mLocation; }
        }

        /// <summary>
        /// Evaluates the probability density function for a Cauchy distribution.
        /// </summary>
        public double Density(double x)
        {
            return 1.0 / (Math.Constants.Pi * mScale * (1.0 + ((x - mLocation) / mScale) * ((x - mLocation) / mScale)));
        }

        /// <summary>
        /// Draws a random sample from the distribution.
        /// </summary>
        /// <returns>A random number from this distribution.</returns>
        public double Sample()
        {
            return DoSample(RandomNumberGenerator, mLocation, mScale);
        }

        /// <summary>
        /// Samples an array of Cauchy distributed random variables.
        /// </summary>
        /// <param name="size">The number of variables needed.</param>
        /// <returns>An array of random numbers from this distribution.</returns>
        public double[] Sample(int size)
        {
            return DoSample(RandomNumberGenerator, size, mLocation, mScale);
        }

        #endregion

        /// <summary>
        /// Checks the parameters of a Cauchy distribution.
        /// </summary>
        /// <param name="scale">The scale of a cauchy distribution.</param>
        /// <exception cref="ArgumentOutOfRangeException">If the scale is not positive.</exception>
        private static void CheckParameters(double scale)
        {
            if (scale <= 0.0)
            {
                throw new ArgumentOutOfRangeException("scale", "Scale cannot be negative.");
            }
        }

        /// <summary>
        /// Evaluates the cumulative distribution function for the Cauchy distribution.
        /// </summary>
        public double CumulativeDistribution(double x)
        {
            return Math.Constants.OneOverPi * System.Math.Atan((x - mLocation) / mScale) + 0.5;
        }

        /// <summary>
        /// Evaluates the inverse cumulative distribution function for the Cauchy distribution.
        /// </summary>
        public double InverseCumulativeDistribution(double p)
        {
            return mLocation + mScale * System.Math.Tan(Math.Constants.Pi * (p - 0.5));
        }

        /// <summary>
        /// Samples a Cauchy distributed random variable using the Inverse CDF method.
        /// </summary>
        /// <param name="rnd">The random number generator to use.</param>
        /// <param name="location">The location of the Cauchy distribution.</param>
        /// <param name="scale">The scale of the Cauchy distribution.</param>
        public static double Sample(System.Random rnd, double location, double scale)
        {
            if (Control.CheckDistributionParameters)
            {
                CheckParameters(scale);
            }

            return DoSample(rnd, location, scale);
        }

        /// <summary>
        /// Samples an array of Cauchy distributed random variables using the Inverse CDF method.
        /// </summary>
        /// <param name="rnd">The random number generator to use.</param>
        /// <param name="n">The number of variables needed.</param>
        /// <param name="location">The location of the Cauchy distribution.</param>
        /// <param name="scale">The scale of the Cauchy distribution.</param>
        public static double[] Sample(System.Random rnd, int n, double location, double scale)
        {
            if (Control.CheckDistributionParameters)
            {
                CheckParameters(scale);
            }

            return DoSample(rnd, n, location, scale);
        }

        private static double DoSample(System.Random rnd, double location, double scale)
        {
            double u = rnd.NextDouble();
            return location + scale * System.Math.Tan(Math.Constants.Pi * (u - 0.5));
        }

        private static double[] DoSample(System.Random rnd, int n, double location, double scale)
        {
            double[] arr = new double[n];
            for (int i = 0; i < n; i++)
            {
                arr[i] = DoSample(rnd, location, scale);
            }
            return arr;
        }
    }
}